package com.onlyphoto.onlymall.mvp.view.activity

import android.content.Intent
import android.graphics.drawable.Drawable
import android.graphics.drawable.StateListDrawable
import android.view.View
import android.view.ViewGroup
import android.widget.RadioGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.onlyphoto.onlymall.base.BaseActivity
import com.bumptech.glide.Glide
import com.onlyphoto.onlymall.bean.RedDotBean
import com.onlyphoto.onlymall.bean.TabbarListBean
import com.onlyphoto.onlymall.mvp.contract.CMain
import com.onlyphoto.onlymall.mvp.presenter.PMainImpl
import com.onlyphoto.onlymall.mvp.view.fragment.HomePageFragment
import com.onlyphoto.onlymall.mvp.view.fragment.ShopFragment
import com.onlyphoto.onlymall.mvp.view.fragment.MyFragment
import com.onlyphoto.onlymall.utils.Constants
import com.onlyphoto.onlymall.utils.ConvertUtil
import com.onlyphoto.onlymall.widget.RedDotRadioButton
import kotlinx.android.synthetic.main.activity_main.*
import com.onlyphoto.onlymall.R
import com.onlyphoto.onlymall.api.Urls
import com.onlyphoto.onlymall.bean.response.Rotation
import com.onlyphoto.onlymall.bean.response.SingleActivityBean
import com.onlyphoto.onlymall.events.ChangeTabEvent
import com.onlyphoto.onlymall.mvp.view.fragment.CategoryFragment
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode



class MainActivity : BaseActivity<PMainImpl>(), CMain.IVMain {

    private var homePageFragment: HomePageFragment? = null
    private var categoryFragment: CategoryFragment? = null
    private var shopFragment: ShopFragment? = null
    private var myFragment: MyFragment? = null
    var redDot: RedDotBean? = null
    private var currentIndex = Constants.PAGE_HOME_INDEX

    var tabbar: TabbarListBean? = null
    private var lastTime: Long = 0

    private val fragmentManager by lazy {
        supportFragmentManager
    }

    companion object {
        const val PAGE_INDEX = "PAGE_INDEX"
    }

    override fun retry() {}

    override fun init() {
        //将"发现"图标变大
        /*var drs = rb_discover.compoundDrawables
        //给drawable设置边界("发现"的图片变大)
        var r = Rect(0, 0, drs[1].minimumWidth * 5 / 3, drs[1].minimumHeight * 5 / 3)
        drs[1].bounds = r
        rb_discover.setCompoundDrawables(null, drs[1], null, null)*/

        rg_bottom.run {
            setOnCheckedChangeListener(checkedChangeListener)
        }
        getPageIndexData()
    }

    override fun initListener() {
        //点击事件初始化
    }

    override fun loadData() {
        mPresenter!!.requestData()
    }

    override fun isFullScreen(): Boolean {
        //是否沉浸式， 默认非沉浸式
        return false
    }

    public override fun initCustomerStatusManager() {

    }

    /**
     * 初始化fragment
     */
    fun initFragment(items: List<TabbarListBean.TabbarItem>?) {
        val size = ConvertUtil.dp2px(this@MainActivity, 26F)
        var firstId = 0
        fragmentManager.beginTransaction().apply {
            items?.forEachIndexed { index, it ->
                when (it.tag) {
                    1 -> { //首页
                        if (index == 0) {
                            firstId = R.id.rb_home
                        }
                        drawRemoteTabBar(it, R.id.rb_home, size, index == 0)
                        homePageFragment ?: let {
                            HomePageFragment().let {
                                homePageFragment = it
                                add(R.id.fl_container, homePageFragment!!)
                            }
                        }
                    }
                    2 -> { //分类
                        if (index == 0) {
                            firstId = R.id.rb_category
                        }
                        drawRemoteTabBar(it, R.id.rb_category, size, index == 0)
                        categoryFragment ?: let {
                            CategoryFragment().let {
                                categoryFragment = it
                                add(R.id.fl_container, categoryFragment!!)
                            }
                        }
                    }
                    /*3 -> { //发现
                        if (index == 0) {
                            firstId = R.id.rb_discover
                        }
                        drawRemoteTabBar(it, R.id.rb_discover, size, index == 0)
                        shopFragment ?: let {
                            ShopFragment().let {
                                shopFragment = it
                                add(R.id.fl_container, shopFragment!!)
                            }
                        }
                    }*/
                    3 -> { //购物车
                        if (index == 0) {
                            firstId = R.id.rb_shop
                        }
                        drawRemoteTabBar(it, R.id.rb_shop, size, index == 0)
                        shopFragment ?: let {
                            ShopFragment().let {
                                shopFragment = it
                                add(R.id.fl_container, shopFragment!!)
                            }
                        }
                    }
                    4 -> { //我的
                        if (index == 0) {
                            firstId = R.id.rb_account
                        }
                        drawRemoteTabBar(it, R.id.rb_account, size, index == 0, redDot != null && redDot?.is_show != 0)
                        myFragment ?: let {
                            MyFragment().let {
                                myFragment = it
                                add(R.id.fl_container, myFragment!!)
                            }
                        }
                    }
                }
            }
        }.commitAllowingStateLoss()
        switchFragment(firstId)
    }

    override fun defaultView() {
        if (tabbar == null || tabbar?.item == null || tabbar?.item?.size == 0) {
            fragmentManager.beginTransaction().apply {
                homePageFragment?: let {
                    HomePageFragment().let {
                        homePageFragment = it
                        add(R.id.fl_container, homePageFragment!!)
                    }
                }
                categoryFragment?: let {
                    CategoryFragment().let {
                        categoryFragment = it
                        add(R.id.fl_container, categoryFragment!!)
                    }
                }
                shopFragment?: let {
                    ShopFragment().let {
                        shopFragment = it
                        add(R.id.fl_container, shopFragment!!)
                    }
                }
                myFragment?: let {
                    MyFragment().let {
                        myFragment = it
                        add(R.id.fl_container, myFragment!!)
                    }
                }
                hideFragments(this)
            }.commitAllowingStateLoss()
            rb_home.isChecked = true
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        getPageIndexData()
    }

    private fun getPageIndexData() {
        if (intent.hasExtra(PAGE_INDEX)) {
            currentIndex = intent.getIntExtra(PAGE_INDEX, Constants.PAGE_HOME_INDEX)
            switchFragment(currentIndex)
        }
    }

    private val checkedChangeListener = RadioGroup.OnCheckedChangeListener { _, checkedId ->
        switchFragment(checkedId)
    }

    /**
     * 切换fragment
     */
    private fun switchFragment(id: Int) {
        fragmentManager.beginTransaction().apply {
            hideFragments(this)
            when (id) {
                Constants.PAGE_HOME_INDEX ->
                    homePageFragment?.let {
                        currentIndex = id
                        this.show(it)
                        rb_home?.let {
                            if (!rb_home.isChecked) {
                                rb_home.isChecked = true
                            }
                        }
                    }
                Constants.PAGE_CATEGORY_INDEX ->
                    categoryFragment?.let {
                        currentIndex = id
                        this.show(it)
                        rb_category?.let {
                            if (!rb_category.isChecked) {
                                rb_category.isChecked = true
                            }
                        }
                    }
                Constants.PAGE_SHOP_INDEX ->
                    shopFragment?.let {
                        currentIndex = id
                        this.show(it)
                        rb_shop?.let {
                            if (!rb_shop.isChecked) {
                                rb_shop.isChecked = true
                            }
                        }
                    }
                Constants.PAGE_ACCOUNT_INDEX ->
                    myFragment?.let {
                        currentIndex = id
                        this.show(it)
                        rb_account?.let {
                            if (!rb_account.isChecked) {
                                rb_account.isChecked = true
                            }
                        }
                    }
            }
        }.commitAllowingStateLoss()
    }

    /**
     * 隐藏所有fragment
     */
    private fun hideFragments(transaction: FragmentTransaction) {
        homePageFragment?.let {
            transaction.hide(it)
        }
        shopFragment?.let {
            transaction.hide(it)
        }
        categoryFragment?.let {
            transaction.hide(it)
        }
        myFragment?.let {
            transaction.hide(it)
        }
    }

    override fun onBackPressed() {
        var currentTime = System.currentTimeMillis()
        if (currentTime - lastTime < 2000) {
            super.onBackPressed()
            finish()
        } else {
            showToast("再按一次退出程序")
            lastTime = currentTime
        }
    }

    private fun drawRemoteTabBar(it: TabbarListBean.TabbarItem, id: Int, size: Int, isChecked: Boolean, redDot: Boolean = false) {
        try {
            val view: RedDotRadioButton = View.inflate(this, R.layout.view_tab_bar_item, null) as RedDotRadioButton
            val params = RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)
            params.weight = 1.0F
            view.layoutParams = params
            view.id = id
            view.text = it.title

            view.isChecked = isChecked

            view.setRedOn(redDot)

            var normal = false
            var checked = false
            val checkDrawable = StateListDrawable()
            checkDrawable.setBounds(0, 0, size, size)

            Glide.with(this).asDrawable().load(it.image).into(object : CustomTarget<Drawable>(){
                override fun onLoadCleared(placeholder: Drawable?) {

                }

                override fun onResourceReady(drawable: Drawable, transition: Transition<in Drawable>?) {
                    drawable.setBounds(0, 0, size, size)
                    checkDrawable.addState(intArrayOf(-android.R.attr.state_checked), drawable)
                    normal = true
                    if (checked) {
                        view.setCompoundDrawables(null, checkDrawable, null, null)
                    }
                }

            })

            Glide.with(this).asDrawable().load(it.Red_dot_image).into(object : CustomTarget<Drawable>(){
                override fun onLoadCleared(placeholder: Drawable?) {

                }

                override fun onResourceReady(drawable: Drawable, transition: Transition<in Drawable>?) {
                    drawable.setBounds(0, 0, size, size)
                    checkDrawable.addState(intArrayOf(android.R.attr.state_checked), drawable)
                    checked = true
                    if (normal) {
                        view.setCompoundDrawables(null, checkDrawable, null, null)
                    }
                }

            })
            rg_bottom.addView(view)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 防止fragment重叠
     */
    override fun onAttachFragment(fragment: Fragment) {
        super.onAttachFragment(fragment)
        when (fragment) {
            is HomePageFragment -> homePageFragment ?: let { homePageFragment = fragment }
            is ShopFragment -> shopFragment ?: let { shopFragment = fragment }
            is CategoryFragment -> categoryFragment ?: let { categoryFragment = fragment }
            is MyFragment -> myFragment ?: let { myFragment = fragment }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(bean: Rotation) {
        when (bean.turn_type) {
            3 -> {
                switchFragment(Constants.PAGE_CATEGORY_INDEX)
                EventBus.getDefault().post(bean.turn_url)
            }
            4 -> {
                startActivity(Intent(this, GoodsListActivity::class.java)
                        .putExtra("cart2Id", bean.turn_url))
            }
            5 -> {
                startActivity(Intent(this, WebViewActivity::class.java)
                        .putExtra("url", Urls.RAIDERS + bean.turn_url))
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(bean: SingleActivityBean) {
        when (bean.turn_type) {
            3 -> {
                switchFragment(Constants.PAGE_CATEGORY_INDEX)
                EventBus.getDefault().post(bean.turn_url)
            }
            4 -> {
                startActivity(Intent(this, GoodsListActivity::class.java)
                        .putExtra("cart2Id", bean.turn_url))
            }
            5 -> {
                startActivity(Intent(this, WebViewActivity::class.java)
                        .putExtra("url", Urls.RAIDERS + bean.turn_url))
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: ChangeTabEvent) {
        when (event.tabName) {
            Constants.PAGE_CATEGORY_INDEX ->
                switchFragment(Constants.PAGE_CATEGORY_INDEX)
            Constants.PAGE_SHOP_INDEX ->
                switchFragment(Constants.PAGE_SHOP_INDEX)

        }
    }

    override fun setContentViewId(): Int {
        return R.layout.activity_main
    }

    override fun createPresenter() {
        mPresenter = PMainImpl(mContext, this)
    }

    override fun showLoading() {

    }

    override fun hideLoading() {

    }

}
